﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using LitJson;
using System.Web;
using He.Common;
using System.Text.RegularExpressions;

namespace He.API.Translate.Bing
{
    public class TranslateHelper
    {
        /// <summary>
        /// 获取Bing AccessToken
        /// </summary>
        /// <returns></returns>
        public static string GetAccessToken()
        {
            string access_token = CookieHelper.Get(SysKeys.BING_ACCESS_TOKEN_COOKIE_NAME);
            if (string.IsNullOrEmpty(access_token))
            {
                Model.webset webset = new BLL.webset().GetWebset();
                string clientID = webset.bing_client_id;
                string clientSecret = webset.bing_client_secret;

                String strTranslatorAccessURI = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
                String strRequestDetails = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=http://api.microsofttranslator.com", HttpUtility.UrlEncode(clientID), HttpUtility.UrlEncode(clientSecret));

                System.Net.WebRequest webRequest = System.Net.WebRequest.Create(strTranslatorAccessURI);
                webRequest.ContentType = "application/x-www-form-urlencoded";
                webRequest.Method = "POST";

                byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strRequestDetails);
                webRequest.ContentLength = bytes.Length;
                using (System.IO.Stream outputStream = webRequest.GetRequestStream())
                {
                    outputStream.Write(bytes, 0, bytes.Length);
                }
                System.Net.WebResponse webResponse = webRequest.GetResponse();

                StreamReader reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8);
                string jsonStr = reader.ReadToEnd();
                reader.Close();
                AdmAccessToken AccessToken = JsonMapper.ToObject<AdmAccessToken>(jsonStr);
                access_token = AccessToken.access_token;
                CookieHelper.Set(SysKeys.BING_ACCESS_TOKEN_COOKIE_NAME, access_token, Convert.ToInt32(AccessToken.expires_in));
            }
            return access_token;
        }

        /// <summary>
        /// Bing翻译
        /// </summary>
        /// <param name="txt"></param>
        /// <param name="isDropHtml"></param>
        /// <returns></returns>
        public static string Translate(string txt, bool isDropHtml)
        {
            if (isDropHtml)
            {
                //过滤HTML标签
                txt = StringHelper.DropHtmlTags(txt);
            }

            //获取access_token
            string access_token = GetAccessToken();
            string headerValue = "Bearer " + access_token;

            //根据access_token进行翻译
            int len = 1000;//每段翻译的字符长度
            string[] strArr = StringHelper.StringToArr(txt, len);//将字符串进行分段处理
            StringBuilder strTemp = new StringBuilder();
            foreach (string item in strArr)
            {
                string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(item) + "&from=zh-CN&to=en";
                System.Net.WebRequest translationWebRequest = System.Net.WebRequest.Create(uri);
                translationWebRequest.Headers.Add("Authorization", headerValue);
                System.Net.WebResponse response = null;
                response = translationWebRequest.GetResponse();
                System.IO.Stream stream = response.GetResponseStream();
                System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
                System.IO.StreamReader translatedStream = new System.IO.StreamReader(stream, encode);
                System.Xml.XmlDocument xTranslation = new System.Xml.XmlDocument();
                xTranslation.LoadXml(translatedStream.ReadToEnd());
                strTemp.Append(xTranslation.InnerText);
            }
            return strTemp.ToString();
        }
    }
}
